package com.apes.autoparts.product.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.autoparts.product.model.BrandProduct;
import com.apes.autoparts.product.model.OriginalProduct;
import com.apes.autoparts.product.repository.BrandProductRepository;
import com.apes.autoparts.product.repository.ProductDao;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;

/**
 * 类描述：品牌件全车标准商品服务类
 *
 * @ClassName brandProductService
 * @Description 描述
 * @Author wushilong
 * @Date 2022/10/9 10:06
 * @Version 1.0
 */

@Service
public class BrandProductService extends DomainService {

    @Autowired
    private BrandProductRepository brandProductRepository;

    @Autowired
    private ProductDao productDao;

    /**
     * 批量更新、新增、删除
     *
     * @param request
     * @return
     */
    public Map edit(SimpleRequest request) {
        //新增和修改
        List<BrandProduct> brandProducts = request.getA("brandProductItems", BrandProduct.class);
        Set<String> brandPrioritySet = new HashSet<>();
        List<BrandProduct> newBrandProduct = new ArrayList<>();

        //禁止添加重复数据
        brandProducts.forEach(brandProduct -> {
            String sole = brandProduct.getBrand() + brandProduct.getBrandMark();
            if (!brandPrioritySet.add(sole)) throw new RuntimeException("请勿添加重复数据，请检查添加数据是否正确！");
            if (Objects.isNull(brandProduct.getId()) || "0".equals(brandProduct.getId()))
                newBrandProduct.add(brandProduct);
        });

        //获取删除的数据,如果没有不删除
        if (Objects.nonNull(request.getJO().get("del"))) {
            List<BrandProduct> delBrandProducts = request.getA("del", BrandProduct.class);
            delBrandProducts.forEach(brandProduct -> {
                String sole = brandProduct.getBrand() + brandProduct.getBrandMark();
                ;
                if (Objects.nonNull(brandProduct.getId()) && brandPrioritySet.add(sole)) {
                    brandProductRepository.delete(brandProduct);
                }
            });
        }
        //批量插入品牌件全车标准商品
        productDao.brandBatchInsert(newBrandProduct);

        return MapUtil.mapper("brandProductItems", newBrandProduct);
    }

    /**
     * 定制导入品牌标准商品
     *
     * @param request
     */
    public JSONObject importBrandProduct(SimpleRequest request) {
        //Excel信息
        JSONObject importData = request.get("importData");
        JSONArray titleColumnArray = new JSONArray();
        String key = appendImportReturn_New(importData, titleColumnArray);
        JSONObject returnData = new JSONObject();
        returnData.put(key, titleColumnArray);
        return returnData;
    }

    /**
     * 并行流导入
     *
     * @param importData
     * @param titleColumnArray
     * @return
     */
    private String appendImportReturn_New(JSONObject importData, JSONArray titleColumnArray) {

        AtomicReference<String> key = new AtomicReference<>();
        Set<String> stringHashSet = new HashSet<>();

        JSONArray titleArray = new JSONArray(3);
        titleArray.add("标准名称");
        titleArray.add("品牌");
        titleArray.add("品牌件号");
        titleArray.add("ERP商品编码");
        titleColumnArray.add(titleArray);

        List<BrandProduct> dataList = Collections.synchronizedList(new ArrayList());
        importData.forEach((k, v) -> {
            key.set(k);
            JSONArray importDataValueArray = (JSONArray) v;
            if (((JSONArray) importDataValueArray.get(0)).size() != 4) throw new RuntimeException("导入模板错误，请检查文件并重新上传！");
            importDataValueArray.parallelStream().forEach(item -> {
                JSONArray iValueArray = (JSONArray) item;
                if (iValueArray.size() == 0) return;

                String name = iValueArray.get(0).toString();
                String brand = iValueArray.get(1).toString();
                String brandMark = iValueArray.get(2).toString();
                String ERPProductId = "";
                if (iValueArray.size() == 4) ERPProductId = iValueArray.get(3).toString();

                if (Pattern.matches("[\\u4e00-\\u9fa5]*", brandMark)) {    // 匹配中文
                    return;
                }

                if (!stringHashSet.add(name + brand + brandMark)) throw new RuntimeException("导入重复数据，请重新导入！");

                BrandProduct brandProduct = new BrandProduct();
                brandProduct.setName(name);
                brandProduct.setBrand(brand);
                brandProduct.setBrandMark(brandMark);
                brandProduct.setERPProductId(ERPProductId);

                dataList.add(brandProduct);
            });
        });

        //批量插入品牌件全车标准商品
        productDao.brandBatchInsert(dataList);
        return key.get();
    }

    /**
     * 放弃编辑回显当前数据
     *
     * @param request
     * @return
     */
    public Map brandProductFindOne(SimpleRequest request) {
        List<BrandProduct> list = request.getA("brandProductItems", BrandProduct.class);
        return MapUtil.mapper("brandProductItems", list);
    }

    /**
     * 动态条件查询
     *
     * @param request
     */
    public Map conditionQuery(SimpleRequest request) {
        JSONObject jo = request.getJO();

        String name = jo.getString("name");
        String brand = jo.getString("brand");
        String brandMark = jo.getString("brandMark");
        int page = jo.getInteger("page") < 0 || jo.getInteger("page")==null ? 0 : jo.getInteger("page");
        if ("".equals(name)) name = null;
        if ("".equals(brand)) brand = null;
        if ("".equals(brandMark)) brandMark = null;

        if (Objects.isNull(name) && Objects.isNull(brand) && Objects.isNull(brandMark)) {
            Page<BrandProduct> brandProductPage = brandProductRepository.findAll(PageRequest.of(page, 50, Sort.by(Sort.Direction.DESC, "id")));
            return MapUtil.mapper("content", brandProductPage.getContent(), "page", page, "sum", brandProductPage.getTotalPages());
        }
        Page<BrandProduct> brandProductPage = brandProductRepository.findAll(JpaDsl.toCriteriaIgnoreNull("name", "EQ", name,
                "brand", "EQ", brand,
                "brandMark", "EQ", brandMark),
                PageRequest.of(page, 50, Sort.by(Sort.Direction.DESC, "id")));
        return MapUtil.mapper("content", brandProductPage.getContent(), "page", page, "sum", brandProductPage.getTotalPages());
    }

    /**
     * 下载
     *
     * @param request
     * @return
     */
    public Map download(SimpleRequest request) {
        JSONObject jo = request.getJO();
        JSONObject condition = jo.getJSONObject("condition");
        String name = condition.getString("name");
        String brand = condition.getString("brand");
        String brandMark = condition.getString("brandMark");
        if (Objects.isNull(name) && Objects.isNull(brand) && Objects.isNull(brandMark)) {
            Page<BrandProduct> page = brandProductRepository.findAll(PageRequest.of(request.get("page"), request.get("size"), Sort.by(Sort.Direction.DESC, "id")));
            return MapUtil.mapper("content", page.getContent(), "total", page.getTotalElements(), "pages", page.getTotalPages(), "page", request.get("page"));
        }

        Page<BrandProduct> page = brandProductRepository.findAll(JpaDsl.toCriteriaIgnoreNull("name", "EQ", name,
                "brand", "EQ", brand,
                "brandMark", "EQ", brandMark),
                PageRequest.of(request.get("page"), request.get("size"), Sort.by(Sort.Direction.DESC, "id")));
        return MapUtil.mapper("content", page.getContent(), "total", page.getTotalElements(), "pages", page.getTotalPages(), "page", request.get("page"));
    }


    /**
     * 批量删除
     *
     * @param request
     * @return
     */
    public Map delbrandProduct(SimpleRequest request){
        List<BrandProduct> delbrandProducts = request.getA("del", BrandProduct.class);
        for (BrandProduct brandProduct : delbrandProducts) {
            brandProductRepository.delete(brandProduct);
        }
        request.setBody(request.getJO().getString("model"));
        return conditionQuery(request);
    }


    /**
     * 添加
     * @param request
     * @return
     */
    public BrandProduct insertbrandProduct(SimpleRequest request){
        JSONObject jo = request.getJO();
        BrandProduct brandProduct  = jo.getObject("data",BrandProduct.class);
        try{
            brandProduct =  brandProductRepository.saveAndFlush(brandProduct);
            return brandProduct;
        }catch (Exception e) {
            throw new RuntimeException("添加失败，品牌加品牌件号不能重复！");
        }
    }

    /**
     * 根据品牌+零件号获取标准商品
     * @param request
     * @return
     */
    public BrandProduct getBrandProduct(SimpleRequest request){
        JSONObject param = request.getJO();
        String brand = param.getString("brand");
        String brandMark = param.getString("brandMark");
        return brandProductRepository.findByBrandAndBrandMark(brand, brandMark);
    }
}
